# #coding:utf-8

import os
import sys
from qs import SqlRunner, Qs
import win32event
import win32service
import win32serviceutil
import servicemanager
import winerror

# 以管理员身份运行
# python xxx.py install 安装
# python xxx.py start启动
# python xxx.py --startup auto install
# python xxx.py stop停止
# python xxx.py debug调试
# python xxx.py remove删除

qs = Qs()
runner = SqlRunner()


class Service(win32serviceutil.ServiceFramework):
    _svc_name_ = 'filesearch'
    _svc_display_name_ = 'filesearch'

    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
        self.run = True
        print('startting....')

    def SvcDoRun(self):
        servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
                              servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, ''))
        self.timeout = 100
        qs.run()
        while self.run:
            rc = win32event.WaitForSingleObject(self.hWaitStop, self.timeout)
            if rc == win32event.WAIT_OBJECT_0:
                break
            else:
                runner.run()

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)
        self.run = False
        return


if __name__ == "__main__":
    if len(sys.argv) == 1:
        try:
            evtsrc_dll = os.path.abspath(servicemanager.__file__)
            servicemanager.PrepareToHostSingle(Service)
            servicemanager.Initialize('Service', evtsrc_dll)
            servicemanager.StartServiceCtrlDispatcher()
        except win32service.error as error:
            if error.args[0] == winerror.ERROR_FAILED_SERVICE_CONTROLLER_CONNECT:
                win32serviceutil.usage()
    else:
        win32serviceutil.HandleCommandLine(Service)
